1102B - Array K-Coloring - CodeForces Solution


greedy sortings *1400

Please click on ads to support us..

Python Code:

from collections import defaultdict
import math

n, k = map(int, input().split())

values = list(map(int, input().split()))

def K_colors(nums, k):
    values = sorted([(val, i) for i, val in enumerate(nums)])
    i = 0
    color = 1
    res = [0] * len(values)

    while i < len(values):
        j = i
        count = 0
        while j < len(values) and values[i][0] == values[j][0]:
            
            if count == k:
                return []
            res[values[j][1]] = color 
            count += 1
            color += 1
            if color == k+1:
                color = 1
            j += 1
        i = j

    return res


result = K_colors(values, k)
if result:
    print("YES")
    for val in result:
        print(val, end = " ")
else:
    print("NO")

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long

int32_t main(){
  int n, k;
  cin>>n>>k;
  vector<int> v(n);
  map<int, vector<int>> mp;
  for(int i=0;i<n;i++){
    cin>>v[i];
    mp[v[i]].push_back(i);
  }
  bool flag=false;
  for(auto it: mp)
     if(it.second.size()>k)
        flag=true;
  if(k>n)
     cout<<"NO"<<'\n';
  else if(flag)
     cout<<"NO"<<'\n';
  else{
     cout<<"YES"<<'\n';
     int start=1;
     if(k==1){
        for(int i=0;i<n;i++)
          cout<<1<<" ";
          cout<<'\n';
     }
     else{
     for(auto it: mp){
        for(auto itr: it.second){
            if(start>k)
              start%=k;
            v[itr]=start;
            start++;
        }
     }
        for(auto it: v)
          cout<<it<<" ";
        cout<<'\n';
    }
  }
  return 0;
}


Comments

Submit
0 Comments
More Questions

1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum
474A - Keyboard
1343A - Candies
1343C - Alternating Subsequence
1325A - EhAb AnD gCd
746A - Compote
318A - Even Odds
550B - Preparing Olympiad
939B - Hamster Farm
732A - Buy a Shovel
1220C - Substring Game in the Lesson
452A - Eevee
1647B - Madoka and the Elegant Gift
1408A - Circle Coloring
766B - Mahmoud and a Triangle
1618C - Paint the Array
469A - I Wanna Be the Guy
1294A - Collecting Coins
1227A - Math Problem
349A - Cinema Line
47A - Triangular numbers
1516B - AGAGA XOOORRR
1515A - Phoenix and Gold
1515B - Phoenix and Puzzle
155A - I_love_username
49A - Sleuth
1541A - Pretty Permutations